package org.dragon.services.impls;

import jakarta.annotation.Resource;
import org.dragon.commons.Times;
import org.dragon.mappers.PrivilegeMapper;
import org.dragon.models.Privilege;
import org.dragon.models.PrivilegeExtend;
import org.dragon.services.PermissionService;
import org.dragon.services.PrivilegeService;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * Author:     Zhao Yan
 * DateTime:   2023/5/23 8:53
 */
@Service
public class PrivilegeServiceImpl implements PrivilegeService {

    @Resource
    private PrivilegeMapper privilegeMapper;

    @Resource
    private PermissionService permissionService;

    @Cacheable(value = "privileges", key = "'all'", sync = true)
    @Override
    public List<PrivilegeExtend> findAll() {
        var list = privilegeMapper.selectAll();
        var result = new ArrayList<PrivilegeExtend>();

        for (Privilege p : list) {
            var ext = new PrivilegeExtend();
            ext.privilege = p;
            ext.permissions = permissionService.findByPrivilegeId(p.getId());
            result.add(ext);
        }

        return result;
    }

    @CacheEvict(value = "privileges", allEntries = true)
    @Override
    public void save(Privilege privilege) {
        if (privilege != null) {
            if (privilege.getId() == null) {
                privilege.setCreateTime(Times.now());
                privilegeMapper.insert(privilege);
            } else
                privilegeMapper.updateByPrimaryKey(privilege);
        }
    }
}
